<template>
	<div class="pay-container">
		<!-- 生成微信支付二维码 -->
		<div class="erwei">
			<img :src="qrUrl"
				alt="" />
		</div>
		<svg class="icon"
			aria-hidden="true">
			<use xlink:href="#icon-wechat_pay"></use>
		</svg>
		<span>使用微信进行支付</span>
		<el-descriptions title="订单详情">
			<el-descriptions-item label="订单号">{{order.order_id}}</el-descriptions-item>
			<el-descriptions-item label="创建时间">{{order.create_time}}</el-descriptions-item>
			<el-descriptions-item label="产品名称">{{order_detail.productName}}</el-descriptions-item>
			<el-descriptions-item label="商品描述">{{order_detail.description}}</el-descriptions-item>
			<el-descriptions-item label="购买数量">{{order_detail.quantity}}</el-descriptions-item>
			<el-descriptions-item label="购买用户">{{order.user_nickname}}</el-descriptions-item>
			<el-descriptions-item label="地址">{{order.address}}</el-descriptions-item>
			<el-descriptions-item label="手机号">{{order.user_phone}}</el-descriptions-item>
			<el-descriptions-item label="总价格">{{order.total_fee}} </el-descriptions-item>
		</el-descriptions>
	</div>
</template>
<script>
	import qr from "qrcode";
	import * as payApi from "@/api/pay";
	//1.需要通过订单的id获取订单详情
	//2.根据订单id请求支付接口
	//3.通过轮询,查询支付状态
	export default {
		data() {
			return {
				qrUrl: "", //支付二维码图片地址
				order_detail: {}, //訂單詳情
				order: {},
				order_id: "",
			};
		},
		methods: {
			queryOrderStatus() {
				//使用定时器发送请求 1秒轮询一次
				this.queryInterval = setInterval(async () => {
					let res = await payApi.queryOrderStatus(this.order_id);
					console.log(res);
					if (res.data.status === 200) {
						//支付成功
						//跳转到支付成功的页面
						this.$router.push({ name: "paySuccess" });
					}
				}, 2000);
			},
		},
		async created() {
			//并发请求,请求详情,请求支付
			let order_id = this.$route.query.order_id;
			this.order_id = order_id; //添加到组件实例
			// console.log(order_id);
			if (!order_id) {
				this.$router.push("/vipmanager/charge"); //返回到充值页
				return;
			}
			let res = await Promise.all([
				payApi.getOrder(order_id),
				payApi.startPay(order_id),
			]);

			//发起轮询查询结果

			this.queryOrderStatus();

			// console.log(res);

			//订单详情赋值
			this.order_detail = res[0].data.data.orderDetail[0];
			this.order = res[0].data.data;

			//判断订单是否重复递交
			if (!res[1].data.state) {
				this.$router.push("/vipmanager/charge"); //返回充值页
				return;
			}

			//需要生成二维码

			let payUrl = res[1].data.code_url;
			//下载qrcode插件,生成二维码

			qr.toDataURL(payUrl, (err, imgBase64Url) => {
				if (err) {
					//出错的情况
					this.$messageBox.error(err);
					return;
				}
				// console.log(imgBase64Url);
				this.qrUrl = imgBase64Url;
			});
		},
		beforeDestroy() {
			//清空定时器
			clearInterval(this.queryInterval);
		},
	};
</script>
